import { ref } from 'vue';
import workstationRequest from '@/api/md/workstation/workstation.js';

export const workstationList = ref([]);  // 全部数据
export const pagedData = ref([]);  // 分页后的数据
export const total = ref(0);  // 总数据条数
export const pageSize = ref(10);  // 每页条数
export const currentPage = ref(1);  // 当前页码

// 查询条件
export const searchWorkstation = ref({
    workstationCode: '',
    workstationName: '',
    workshopName: '',
    processName: '',
});

// 分页处理函数
export function handlePageChange(page) {
    currentPage.value = page;
    paginateData();
}

// 根据当前页码和每页条数分页
export function paginateData() {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    pagedData.value = workstationList.value.slice(start, end);
}

// 获取数据
export function fetchWorkstationList(searchWorkstation) {
    workstationRequest.loadWorkstationList(searchWorkstation, function (data) {
        workstationList.value = data.data;
        total.value = workstationList.value.length;  // 设置总条数
        paginateData();  // 设置分页后的数据
    });
}

// 搜索重置
export function resetSearch() {
    searchWorkstation.value.workstationCode = '';
    searchWorkstation.value.workstationName = '';
    searchWorkstation.value.workshopName = '';
    searchWorkstation.value.processName = '';
    fetchWorkstationList(searchWorkstation.value);
}

// 删除选中的单位
export function deleteWorkstations(selectedWorkstations) {
    return new Promise((resolve, reject) => {
        const workstationIds = selectedWorkstations.map(workstation => workstation.workstationId); // 获取选中的workstationId数组
        workstationRequest.deleteWorkstationList(workstationIds, function (res) {
            if (res.code === 200) {
                resolve();
            } else {
                reject(res.message);
            }
        });
    });
}